import mysql from 'mysql'
import mysqlConfig from '@/config/mysql.ts'
import { MySqlLogger } from './Log4jHandler.ts'
import { injectable } from 'inversify'

@injectable()
export class MySqlHandler {
  private MySqlInstance: mysql.Connection | Record<string, any> = {}
  // 创建数据库连接
  createMysqlConnection () {
    const connection = mysql.createConnection({
      host: mysqlConfig.host,
      port: 3306,
      user: mysqlConfig.user,
      password: mysqlConfig.password,
      database: mysqlConfig.database
    })
    this.Instance = connection
    return connection
  }

  // 设置数据库实例
  set Instance (val) {
    this.MySqlInstance = val
  }

  // 获取数据库实例
  get Instance () {
    if (this.MySqlInstance != null) {
      return this.MySqlInstance
    } else {
      MySqlLogger.error('请先初始化数据库实例！')
    }
    return {}
  }
}
